package com.wxzz.elearing.livetelecast.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.livetelecast.amqp.producer.PlatformLivetelecastProducer;
import com.wxzz.elearing.livetelecast.dto.*;
import com.wxzz.elearing.livetelecast.entity.*;
import com.wxzz.elearing.livetelecast.mapper.*;
import com.wxzz.elearing.livetelecast.service.IActivityService;
import com.wxzz.elearing.livetelecast.service.openfeign.IObsApiFeign;
import com.wxzz.elearing.livetelecast.service.openfeign.IUserOrderApiFeign;
import com.wxzz.elearing.livetelecast.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.livetelecast.vo.ActivityFileVo;
import com.wxzz.elearing.livetelecast.vo.ActivityStatisticsVo;
import com.wxzz.elearning.common.constants.OrderConstants;
import com.wxzz.elearning.common.constants.RedisConstants;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.exception.ServiceException;
import com.wxzz.elearning.common.utils.CodeGenerateUtils;
import com.wxzz.elearning.common.utils.ExcelTopicUtils;
import com.wxzz.elearning.common.utils.IPUtils;
import com.wxzz.elearning.common.utils.mobile;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 活动 服务实现类
 * </p>
 *
 * @author
 * @since 2021-04-23
 */
@Slf4j
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityCategoryMapper activityCategoryMapper;

    @Autowired
    private PlatformLivetelecastMapper platformLivetelecastMapper;

    @Override
    public ReturnVO<JgPageVo<List<Activity>>> listActivity(WxActivityDto wxActivityDto) {
        PageHelper.startPage(wxActivityDto.getCurPage(), wxActivityDto.getMaxPage());
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(wxActivityDto.getActivityName())) {
            queryWrapper.like("activity_name", wxActivityDto.getActivityName() + "%");
        }
        if (wxActivityDto.getCategoryId() != null) {
            queryWrapper.eq("activity_category_id", wxActivityDto.getCategoryId());
        }
        if (wxActivityDto.getActivityStatus() != null) {
            queryWrapper.eq("activity_status", wxActivityDto.getActivityStatus());
        }
        if (wxActivityDto.getSort() != null && wxActivityDto.getSort() == 0) {
            queryWrapper.orderByDesc("create_time");
        }
        if (wxActivityDto.getSort() != null && wxActivityDto.getSort() == 1) {
            queryWrapper.orderByAsc("create_time");
        }
        if (wxActivityDto.getStartTime() != null && wxActivityDto.getEndTime() != null) {
            queryWrapper.between("create_time", wxActivityDto.getStartTime(), wxActivityDto.getEndTime());
        }
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        for (Activity activity : activities) {
            PlatformLivetelecast platformLivetelecast = platformLivetelecastMapper.selectById(activity.getPlatformLivetelecastId());
            if (platformLivetelecast != null) {
                //关联直播名称
                activity.setLivetelecastName(platformLivetelecast.getLivetelecastName());
            }
            //查询线下线上人数
            Integer offCount = wxUserPlatformLivetelecastMapper.selectCount(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                    .eq(WxUserPlatformLivetelecast::getType, 1)
                    .eq(WxUserPlatformLivetelecast::getActivityId, activity.getId())
                    .eq(WxUserPlatformLivetelecast::getOnlineType, 0));
            Integer onCount = wxUserPlatformLivetelecastMapper.selectCount(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                    .eq(WxUserPlatformLivetelecast::getType, 1)
                    .eq(WxUserPlatformLivetelecast::getActivityId, activity.getId())
                    .eq(WxUserPlatformLivetelecast::getOnlineType, 1));
            activity.setOffJoinNum(offCount);
            activity.setOnJoinNum(onCount);
            activity.setJoinNum(offCount + onCount);
            //如果为线下活动 并且没有二维码 则生成
            if (activity.getIsOffline() == 1 && StringUtils.isBlank(activity.getActivityUrl())) {
                activity.setActivityUrl(obsApiFeign.makeActivityImage(activity.getId()));
                activityMapper.updateById(activity);
            }
        }
        return new ReturnVO("活动列表查询成功", new JgPageVo<>(new PageInfo(activities)));
    }

    @Autowired
    private IObsApiFeign obsApiFeign;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private PlatformLivetelecastCollectMapper platformLivetelecastCollectMapper;

    @Override
    public ReturnVO<Activity> selectActivityById(Long wxUserId, Long activityId) {
        Activity activity = activityMapper.selectById(activityId);
        Optional.ofNullable(activity).orElseThrow(() -> new ServiceException("该活动不存在"));
        //活动累计访问量
        redisTemplate.opsForValue().increment(RedisConstants.ACTIVITY_VISIT_NUM + activityId, 1);
        //课件
        if (activity != null && activity.getActivityFile() != null) {
            if (activity.getActivityFile() != null && activity.getActivityFileName() != null && activity.getActivityFileSize() != null) {
                String[] files = activity.getActivityFile().split(",");
                String[] fileNames = activity.getActivityFileName().split(",");
                String[] fileSizes = activity.getActivityFileSize().split(",");
                List<ActivityFileVo> activityFileVos = Lists.newArrayList();
                for (int i = 0; i < files.length; i++) {
                    ActivityFileVo activityFileVo = new ActivityFileVo();
                    activityFileVo.setActivityFile(files[i]);
                    activityFileVo.setActivityFileName(fileNames[i]);
                    activityFileVo.setActivityFileSize(fileSizes[i]);
                    activityFileVos.add(activityFileVo);
                }
                activity.setActivityFileVoList(activityFileVos);
            }
        }
        //查询用户是否预约线下
        WxUserPlatformLivetelecast wxUserPlatformLivetelecastOffline = wxUserPlatformLivetelecastMapper.selectOne(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getWxUserId, wxUserId)
                .eq(WxUserPlatformLivetelecast::getActivityId, activityId)
                .eq(WxUserPlatformLivetelecast::getOnlineType, 0));
        if (wxUserPlatformLivetelecastOffline != null) {
            activity.setOfflinePayStatus(wxUserPlatformLivetelecastOffline.getPayStatus());
        }
        //查询用户是否预约线上
        WxUserPlatformLivetelecast wxUserPlatformLivetelecastOnline = wxUserPlatformLivetelecastMapper.selectOne(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getWxUserId, wxUserId)
                .eq(WxUserPlatformLivetelecast::getActivityId, activityId)
                .eq(WxUserPlatformLivetelecast::getOnlineType, 1));
        if (wxUserPlatformLivetelecastOnline != null) {
            activity.setOnlinePayStatus(wxUserPlatformLivetelecastOnline.getPayStatus());
        }
        //查看用户是否收藏
        PlatformLivetelecastCollect platformLivetelecastCollect = platformLivetelecastCollectMapper.selectOne(new LambdaQueryWrapper<PlatformLivetelecastCollect>()
                .eq(PlatformLivetelecastCollect::getWxUserId, wxUserId)
                .eq(PlatformLivetelecastCollect::getType, 1)
                .eq(PlatformLivetelecastCollect::getPlatformLivetelecastId, activity.getId()));
        if (platformLivetelecastCollect != null) {
            activity.setIsCollect(platformLivetelecastCollect.getIsCollect());
        }
        return new ReturnVO("活动详情查询成功", activity);
    }


    @Autowired
    private IUserOrderApiFeign wxPayFeign;

    @Override
    public ReturnVO saveWxUserPlatformLivetelecast4activity(JSONObject jsonObject, WxUserPlatformLivetelecast4activityDto wxUserPlatformLivetelecast4activityDto) {
        //接口幂等处理
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(RedisConstants.WX_USER_COMMENT + jsonObject.getLong("id"), String.valueOf(jsonObject.getLong("id")), 5, TimeUnit.SECONDS);
        if (!Boolean.TRUE.equals(aBoolean)) {
            throw new ServiceException("请重新进入确认是否已经支付成功,以免重复支付");
        }
        Activity activity = activityMapper.selectById(wxUserPlatformLivetelecast4activityDto.getActivityId());
        if (activity == null) {
            throw new ServiceException("该活动id对应活动已不存在");
        }

        //创建预约信息
        WxUserPlatformLivetelecast wxUserPlatformLivetelecast = wxUserPlatformLivetelecastMapper.selectOne(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getWxUserId, jsonObject.getLong("id"))
                .eq(WxUserPlatformLivetelecast::getActivityId, wxUserPlatformLivetelecast4activityDto.getActivityId())
                .eq(WxUserPlatformLivetelecast::getOnlineType, wxUserPlatformLivetelecast4activityDto.getOnlineType())
                .eq(WxUserPlatformLivetelecast::getType, 1));
        //如果未生成过订单 则创建
        if (wxUserPlatformLivetelecast == null) {
            WxUserPlatformLivetelecast save = new WxUserPlatformLivetelecast();
            save.setWxUserId(jsonObject.getLong("id"));
            save.setIcon(jsonObject.getString("icon"));
            save.setRealName(jsonObject.getString("nickname"));
            save.setPhone(jsonObject.getString("phone"));
            save.setActivityId(wxUserPlatformLivetelecast4activityDto.getActivityId());
            save.setOnlineType(wxUserPlatformLivetelecast4activityDto.getOnlineType());
            //查询该活动是否关联直播
            if (activity.getPlatformLivetelecastId() != null) {
                PlatformLivetelecast platformLivetelecast = platformLivetelecastMapper.selectById(activity.getPlatformLivetelecastId());
                if (platformLivetelecast != null) {
                    save.setPlatformLivetelecastId(platformLivetelecast.getId());
                }
            }
            //设置为活动
            save.setType(1);
            wxUserPlatformLivetelecastMapper.insert(save);
            wxUserPlatformLivetelecast = save;
        }
        //未开播时
        if (activity.getActivityStatus() == 0) {
            //自己进入
            if (wxUserPlatformLivetelecast4activityDto.getInvitedWxUserId() == null) {
                wxUserPlatformLivetelecast.setInvitedType(0);
            }
            //受邀请
            if (wxUserPlatformLivetelecast4activityDto.getInvitedWxUserId() != null) {
                wxUserPlatformLivetelecast.setInvitedType(1);
            }
        }
        //直播中
        if (activity.getActivityStatus() == 1) {
            //自己进入
            if (wxUserPlatformLivetelecast4activityDto.getInvitedWxUserId() == null) {
                wxUserPlatformLivetelecast.setInvitedType(2);
            }
            //受邀请
            if (wxUserPlatformLivetelecast4activityDto.getInvitedWxUserId() != null) {
                wxUserPlatformLivetelecast.setInvitedType(3);
            }
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> map = new HashMap();
        map.put("ipaddress", IPUtils.getIpAddr(request));
        map.put("wxUserId", String.valueOf(jsonObject.getLong("id")));
        map.put("serialid", CodeGenerateUtils.generateProductCode());
        //线下价格
        if (wxUserPlatformLivetelecast4activityDto.getOnlineType() == 0) {
            map.put("modelType", OrderConstants.MODEL_TYPE_ACTIVITY_OFF.toString());
            //如果免费直接返回购买成功
            if ("0.00".equals(activity.getOfflinePrice().toString())) {
                wxUserPlatformLivetelecast.setPayStatus(1);
                wxUserPlatformLivetelecastMapper.updateById(wxUserPlatformLivetelecast);
                return new ReturnVO("购买成功", 1);
            }
            map.put("payMoney", activity.getOfflinePrice().toString());
        }
        //线上价格
        if (wxUserPlatformLivetelecast4activityDto.getOnlineType() == 1) {
            map.put("modelType", OrderConstants.MODEL_TYPE_ACTIVITY.toString());
            //如果免费直接返回购买成功
            if ("0.00".equals(activity.getOnlinePrice().toString())) {
                wxUserPlatformLivetelecast.setPayStatus(1);
                wxUserPlatformLivetelecastMapper.updateById(wxUserPlatformLivetelecast);
                return new ReturnVO("订单生成成功", 1);
            }
            map.put("payMoney", activity.getOnlinePrice().toString());
        }
        map.put("businessId", String.valueOf(activity.getId()));
        map.put("orderTitle", "用户购买活动id:" + wxUserPlatformLivetelecast4activityDto.getActivityId());
        map.put("userType", OrderConstants.USER_TYPE_PLATFORM_WX.toString());
        Map<String, String> result = wxPayFeign.orderPay(map);
        wxUserPlatformLivetelecast.setUserOrderId(Long.valueOf(result.get("orderId")));
        wxUserPlatformLivetelecastMapper.updateById(wxUserPlatformLivetelecast);
        return new ReturnVO("订单生成成功", result.get("returnJson"));
    }

    @Override
    public ReturnVO saveActivity(Activity activity) {
        //处理课件
        if (activity.getActivityFileVoList() != null) {
            StringBuilder curriculumFiles = new StringBuilder();
            StringBuilder curriculumFileNames = new StringBuilder();
            StringBuilder curriculumFileSizes = new StringBuilder();
            for (ActivityFileVo curriculumFileVo : activity.getActivityFileVoList()) {
                curriculumFiles.append(curriculumFileVo.getActivityFile()).append(",");
                curriculumFileNames.append(curriculumFileVo.getActivityFileName()).append(",");
                curriculumFileSizes.append(curriculumFileVo.getActivityFileSize()).append(",");
            }
            activity.setActivityFile(curriculumFiles.toString());
            activity.setActivityFileName(curriculumFileNames.toString());
            activity.setActivityFileSize(curriculumFileSizes.toString());
        }
        if (activity.getId() == null) {
            Activity exist = activityMapper.selectOne(new LambdaQueryWrapper<Activity>()
                    .eq(Activity::getPlatformLivetelecastId, activity.getPlatformLivetelecastId()));
            if (exist != null) {
                throw new ServiceException("该直播已绑定活动");
            }
            activityMapper.insert(activity);
        } else {
            Activity exist = activityMapper.selectOne(new LambdaQueryWrapper<Activity>()
                    .eq(Activity::getPlatformLivetelecastId, activity.getPlatformLivetelecastId()));
            if (exist != null && !exist.getPlatformLivetelecastId().equals(activity.getPlatformLivetelecastId())) {
                throw new ServiceException("该直播已绑定活动");
            }
            activityMapper.updateById(activity);
        }
        //自动修改活动开始状态
        if (activity.getActivityStartTime() != null && activity.getActivityStartTime().isAfter(LocalDateTime.now())) {
            platformLivetelecastProducer.updateActivityStartStatus(activity.getId(), activity.getActivityStartTime());
        }
        //自动修改活动结束状态
        if (activity.getActivityStartTime() != null && activity.getActivityEndTime().isAfter(LocalDateTime.now())) {
            platformLivetelecastProducer.updateActivityEndStatus(activity.getId(), activity.getActivityEndTime());
        }
        return new ReturnVO("活动新增或修改成功", activity.getId());
    }

    @Autowired
    private PlatformLivetelecastProducer platformLivetelecastProducer;

    @Override
    public ReturnVO<Activity> selectActivityById(Long activityId) {
        Activity activity = activityMapper.selectById(activityId);
        Optional.ofNullable(activity).orElseThrow(() -> new ServiceException("该活动已经不存在"));
        if (activity.getPlatformLivetelecastId() != null) {
            PlatformLivetelecast platformLivetelecast = platformLivetelecastMapper.selectById(activity.getPlatformLivetelecastId());
            Optional.ofNullable(platformLivetelecast).ifPresent(p -> activity.setLivetelecastName(platformLivetelecast.getLivetelecastName()));
        }
        //查询线下线上人数
        Integer offCount = wxUserPlatformLivetelecastMapper.selectCount(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getType, 1)
                .eq(WxUserPlatformLivetelecast::getActivityId, activity.getId())
                .eq(WxUserPlatformLivetelecast::getOnlineType, 0));
        Integer onCount = wxUserPlatformLivetelecastMapper.selectCount(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getType, 1)
                .eq(WxUserPlatformLivetelecast::getActivityId, activity.getId())
                .eq(WxUserPlatformLivetelecast::getOnlineType, 1));
        activity.setOffJoinNum(offCount);
        activity.setOnJoinNum(onCount);
        activity.setJoinNum(offCount + onCount);
        //课件
        if (activity != null && activity.getActivityFile() != null) {
            if (activity.getActivityFile() != null && activity.getActivityFileName() != null && activity.getActivityFileSize() != null) {
                String[] files = activity.getActivityFile().split(",");
                String[] fileNames = activity.getActivityFileName().split(",");
                String[] fileSizes = activity.getActivityFileSize().split(",");
                List<ActivityFileVo> activityFileVos = Lists.newArrayList();
                for (int i = 0; i < files.length; i++) {
                    ActivityFileVo activityFileVo = new ActivityFileVo();
                    activityFileVo.setActivityFile(files[i]);
                    activityFileVo.setActivityFileName(fileNames[i]);
                    activityFileVo.setActivityFileSize(fileSizes[i]);
                    activityFileVos.add(activityFileVo);
                }
                activity.setActivityFileVoList(activityFileVos);
            }
        }
        return new ReturnVO("活动详情查询成功", activity);
    }

    @Override
    public ReturnVO saveActivityCategory(ActivityCategory activityCategory) {
        if (activityCategory.getId() == null) {
            activityCategoryMapper.insert(activityCategory);
        } else {
            activityCategoryMapper.updateById(activityCategory);
        }
        return new ReturnVO("新增或修改活动分类", activityCategory.getId());
    }

    @Override
    public ReturnVO<JgPageVo<ActivityCategory>> listActivityCategory(ActivityCategoryDto activityCategoryDto) {
        PageHelper.startPage(activityCategoryDto.getCurPage(), activityCategoryDto.getMaxPage());
        List<ActivityCategory> activityCategories = activityCategoryMapper.selectList(new LambdaQueryWrapper<>());
        for (ActivityCategory activityCategory : activityCategories) {
            Integer count = activityMapper.selectCount(new LambdaQueryWrapper<Activity>()
                    .eq(Activity::getActivityCategoryId, activityCategory.getId()));
            activityCategory.setActivityNum(count);
        }
        return new ReturnVO("列出活动分类", activityCategories);
    }

    @Override
    public ReturnVO deleteActivityCategoryById(Long activityCategoryId) {
        activityCategoryMapper.deleteById(activityCategoryId);
        return new ReturnVO("根据id删除活动分类", activityCategoryId);
    }

    @Override
    public ReturnVO<ActivityStatisticsVo> selectActivityStatisticsVoByActivity(Long activityId) {
        Activity activity = activityMapper.selectById(activityId);
        Optional.ofNullable(activity).orElseThrow(() -> new ServiceException("该活动不存在"));
        ActivityStatisticsVo activityStatisticsVo = new ActivityStatisticsVo();
        String activityNum = redisTemplate.opsForValue().get(RedisConstants.ACTIVITY_VISIT_NUM + activityId);
        //累计访问量
        if (StringUtils.isNotBlank(activityNum)) {
            activityStatisticsVo.setActivityVisitNum(Long.valueOf(activityNum));
        }
        //线上报名人数
        Integer countOnline = wxUserPlatformLivetelecastMapper.selectCount(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getActivityId, activityId)
                .eq(WxUserPlatformLivetelecast::getOnlineType, 1)
                .eq(WxUserPlatformLivetelecast::getPayStatus, 1)
                .eq(WxUserPlatformLivetelecast::getType, 1));
        activityStatisticsVo.setActivityOnlineNum(countOnline);
        //线下报名人数
        Integer countOffline = wxUserPlatformLivetelecastMapper.selectCount(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getActivityId, activityId)
                .eq(WxUserPlatformLivetelecast::getOnlineType, 0)
                .eq(WxUserPlatformLivetelecast::getPayStatus, 1)
                .eq(WxUserPlatformLivetelecast::getType, 1));
        activityStatisticsVo.setActivityOfflineNum(countOffline);
        //报名总人数
        activityStatisticsVo.setActivityJoinNum(countOnline + countOffline);
        //线下收入
        BigDecimal offBigDecimal = userOrderApiFeign.selectCountAmount(activityId, 0);
        //线上收入
        BigDecimal OnBigDecimal = userOrderApiFeign.selectCountAmount(activityId, 1);
        if (offBigDecimal != null && OnBigDecimal != null) {
            activityStatisticsVo.setAllOfflineIncome(offBigDecimal);
            activityStatisticsVo.setAllOnlineIncome(OnBigDecimal);
            activityStatisticsVo.setAllJoinIncome(offBigDecimal.add(OnBigDecimal));
        }
        return new ReturnVO("活动统计数据查询成功", activityStatisticsVo);
    }

    @Autowired
    private IUserOrderApiFeign userOrderApiFeign;

    @Override
    public ReturnVO<List<ActivityCategory>> listActivityCategory() {
        List<ActivityCategory> activityCategories = activityCategoryMapper.selectList(new QueryWrapper<>());
        return new ReturnVO("活动分类查询成功", activityCategories);
    }

    @Autowired
    private WxUserPlatformLivetelecastMapper wxUserPlatformLivetelecastMapper;

    @Override
    public ReturnVO<JgPageVo<List<WxUserPlatformLivetelecast>>> listWxUserPlatformLivetelecast(WxInPlatformLivetelecastDto wxInPlatformLivetelecastDto) {
        if (wxInPlatformLivetelecastDto.getActivityId() == null) {
            throw new ServiceException("请传入活动id");
        }
        PageHelper.startPage(wxInPlatformLivetelecastDto.getCurPage(), wxInPlatformLivetelecastDto.getMaxPage());
        List<WxUserPlatformLivetelecast> wxUserPlatformLivetelecasts = wxUserPlatformLivetelecastMapper.selectList(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getPayStatus, 1)
                .eq(WxUserPlatformLivetelecast::getActivityId, wxInPlatformLivetelecastDto.getActivityId()));
        return new ReturnVO("活动报名人查询成功", new JgPageVo<>(new PageInfo(wxUserPlatformLivetelecasts)));
    }

    @SneakyThrows
    @Override
    public ReturnVO importActivity(String token, Long activityId, MultipartFile file) {
        //接口幂等处理
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(RedisConstants.TOPIC_IMPORT + token, token, 5, TimeUnit.SECONDS);
        if (!Boolean.TRUE.equals(aBoolean)) {
            throw new ServiceException("操作太频繁,请5秒后再试");
        }
        Activity activity = activityMapper.selectById(activityId);
        Optional.ofNullable(activity).orElseThrow(() -> new ServiceException("该活动不存在"));
        if (activity.getIsOffline() != 1) {
            throw new ServiceException("活动没有线下活动");
        }
        ExcelTopicUtils excelUtil = new ExcelTopicUtils();
        Workbook wb = excelUtil.getExcel(file);
        Sheet sheet = wb.getSheetAt(0);//读取sheet(从0计数)
        int rowNum = sheet.getLastRowNum();//读取行数(从0计数)
        int i = 0;
        try {
            WxUserPlatformLivetelecast wxUserPlatformLivetelecast = null;
            for (; i <= rowNum; i++) {
                if (i < 1) {
                    //不读前一行
                    continue;
                }
                Row row = sheet.getRow(i);//获得行
                for (int j = 0; j < 4; j++) {
                    Cell cell = row.getCell(j);//获取单元格
                    if (cell != null && StringUtils.isNotBlank(cell.toString())) {
                        if (j == 0) {
                            if (!mobile.isMobile(cell.toString())) {
                                throw new ServiceException("第" + (i + 1) + "行请输入正确的手机号");
                            }
                            WxUserPlatformLivetelecast selectOne = wxUserPlatformLivetelecastMapper.selectOne(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                                    .eq(WxUserPlatformLivetelecast::getActivityId, activityId)
                                    .eq(WxUserPlatformLivetelecast::getOnlineType, 0)
                                    .eq(WxUserPlatformLivetelecast::getPhone, cell.toString()));
                            //查看该用户是否预约
                            if (selectOne == null) {
                                //未购买
                                wxUserPlatformLivetelecast = new WxUserPlatformLivetelecast();
                                wxUserPlatformLivetelecast.setActivityId(activityId);
                                wxUserPlatformLivetelecast.setOnlineType(0);
                                wxUserPlatformLivetelecast.setType(1);
                                wxUserPlatformLivetelecast.setPhone(cell.toString());
                                wxUserPlatformLivetelecastMapper.insert(wxUserPlatformLivetelecast);
                            } else {
                                wxUserPlatformLivetelecast = selectOne;
                            }
                        }
                        if (j == 1) {
                            wxUserPlatformLivetelecast.setRealName(cell.toString());
                        }
                        if (j == 2) {
                            wxUserPlatformLivetelecast.setSeatCode(excelUtil.format(cell.toString()));
                        }
                        if (j == 3) {
                            //如果用户已经购买
                            if (wxUserPlatformLivetelecast.getPayStatus() != null && wxUserPlatformLivetelecast.getPayStatus() == 1) {

                            } else {
                                //并且用户不需要购买 则购买状态直接为已购买
                                if (excelUtil.format(cell.toString()) == 0) {
                                    wxUserPlatformLivetelecast.setPayStatus(1);
                                }
                            }
                            wxUserPlatformLivetelecastMapper.updateById(wxUserPlatformLivetelecast);
                        }
                    }
                }
            }
        } catch (ServiceException e) {
            throw new ServiceException(e.getMessage());
        } catch (Exception e) {
            log.error("导入测评题库出错[{}]", e.getMessage());
            throw new ServiceException("第" + (i + 1) + "行出错");
        }
        return new ReturnVO("导入成功", null);
    }

    @Autowired
    private IWxUserApiFeign wxUserApiFeign;

    @Override
    public ReturnVO activitySignIn(Long wxUserId, Long activityId) {
        FeignWxUserDto feignWxUserDto = wxUserApiFeign.selectFeignWxUserDtoByWxUserId(wxUserId);
        if (feignWxUserDto == null || StringUtils.isBlank(feignWxUserDto.getPhone())) {
            throw new ServiceException("请授权手机号");
        }
        WxUserPlatformLivetelecast wxUserPlatformLivetelecast = wxUserPlatformLivetelecastMapper.selectOne(new LambdaQueryWrapper<WxUserPlatformLivetelecast>()
                .eq(WxUserPlatformLivetelecast::getPhone, feignWxUserDto.getPhone())
                .eq(WxUserPlatformLivetelecast::getActivityId, activityId)
                .eq(WxUserPlatformLivetelecast::getOnlineType, 0)
                .eq(WxUserPlatformLivetelecast::getPayStatus, 1));
        if (wxUserPlatformLivetelecast == null) {
            return new ReturnVO("请先去购买", -1);
        }
        wxUserPlatformLivetelecast.setIsSignIn(1);
        wxUserPlatformLivetelecastMapper.updateById(wxUserPlatformLivetelecast);
        return new ReturnVO("签到成功", wxUserPlatformLivetelecast.getSeatCode());
    }
}
